package com.jt.controller;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.jt.pojo.User;
import com.jt.service.UserService;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisCluster;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    JedisCluster jedisCluster;

    // 用户登录后的回显功能
    @RequestMapping("/user/query/{ticket}")
    public JSONPObject findUserByTicket(@PathVariable String ticket,
                                        HttpServletResponse response,
                                        String callback) {
        String userJson = jedisCluster.get(ticket);
        //1.lru算法清空数据   2.有可能cookie信息有误
        if (StringUtils.isEmpty(userJson)) {
            Cookie cookie = new Cookie("JT_TICKET", "");
            //2.应该删除cookie信息.
            cookie.setMaxAge(0);
            cookie.setDomain("jt.com");
            cookie.setPath("/");
            response.addCookie(cookie);
            return new JSONPObject(callback,SysResult.fail());
        }
        return new JSONPObject(callback,SysResult.success(userJson));
    }
    @RequestMapping("/findAll")
    public List<User> findAll() {
        List<User> list = userService.findAll();
        return list;
    }

    @RequestMapping("/user/check/{param}/{type}")
    public JSONPObject check(@PathVariable String param, @PathVariable Integer type, String callback) {
        boolean flag = userService.checkUser(param, type);
        SysResult sysResult = SysResult.success(flag);
        JSONPObject jsonpObject = new JSONPObject(callback, sysResult);
        return jsonpObject;
    }
    // 前段url http://sso.jt.com/user/testHttpClient
    @RequestMapping("/user/testHttpClient")
    public List<User> testHttpClient() {
        return userService.findAll();
    }
}
